package http

import (
	"blog/app/common"
	"blog/core"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"os"
	"strings"
)

type image struct {
	ID  int    `gorm:"column:img_id"`
	Url string `gorm:"column:image_url"`
	//ID  int    `gorm:"column:goods_id"`
	//Url string `gorm:"column:original_img"`
}

func Ping(c *gin.Context) {
	fmt.Println(common.Cache.File("FqeWqlL6WqCAzxGZFcvdXaTH5r3i"))
}

func ping2(c *gin.Context) {
	//fmt.Println(tools.Tools.Ip.Check("113.74.127.17"))
	client, err := oss.New("http://oss-cn-qingdao.aliyuncs.com", "LTAI5t8jopG86Ebou1Y3uVdo", "dHvXZ88LycCXX0numKg9Wk4FS0sMFq")
	if err != nil {
		fmt.Println("Error-1:", err)
		os.Exit(-1)
	}

	bucket, err := client.Bucket("baiwoimg")
	if err != nil {
		fmt.Println("Error-2:", err)
		os.Exit(-1)
	}
	var data []image
	exitChan := make(chan bool, 5)
	chanUrl := make(chan image, 3)
	numChan := make(chan int, cap(chanUrl))
	core.DbConnect.Table("tp_goods_images").Find(&data)
	//core.DbConnect.Table("tp_goods").Find(&data)
	go start(chanUrl, data)
	for i := 0; i < cap(exitChan); i++ {
		go copy(bucket, chanUrl, exitChan, numChan)
	}

	go func() {
		for i := 0; i < cap(exitChan); i++ {
			<-exitChan
		}
		close(exitChan)
		close(numChan)
	}()

	totalNum := 0
	for {
		num, ok := <-numChan
		if !ok {
			break
		}

		totalNum = totalNum + num

		fmt.Printf("总数：%v,已完成：%v\n", len(data), totalNum)
	}
	fmt.Println(cap(exitChan))
	fmt.Println("完成")
}

func start(chanUrl chan image, data []image) {
	for _, val := range data {
		chanUrl <- val
	}

	close(chanUrl)
}

func copy(bucket *oss.Bucket, chanUrl chan image, exitChan chan bool, numChan chan int) {
	for {
		data, ok := <-chanUrl
		if !ok {
			break
		}

		key := strings.TrimLeft(data.Url, "/")
		selReq := oss.SelectRequest{}
		// 使用SELECT语句查询文件中的数据。
		selReq.Expression = `select * from ossobject`
		body, err := bucket.GetObjectDetailedMeta(key)

		if err != nil {
			fmt.Println("Error-3:", err)
			//os.Exit(-1)
			continue
		}
		// 读取内容。

		if err != nil {
			fmt.Println("Error:", err)
			continue
		}

		if !strings.Contains(key, ".png") && !strings.Contains(key, ".jpg") {
			ext := ""
			switch body.Get("Content-Type") {
			case "image/png":
				ext = "png"
			default:
				ext = "jpg"
			}

			newKey := key + "." + ext
			_, err = bucket.CopyObject(key, newKey)
			if err != nil {
				fmt.Println("Error:", err)
				os.Exit(-1)
			}

			core.DbConnect.Table("tp_goods_images").Where("img_id = ?", data.ID).Update("image_url", "/"+newKey)
			//core.DbConnect.Table("tp_goods").Where("goods_id = ?", data.ID).Update("original_img", "/"+newKey)
		}

		numChan <- 1
	}
	exitChan <- true
}
